<!--
 * @Author: 鸿羽飞舟 2653235481@qq.com
 * @Date: 2022-10-12 14:31:02
 * @LastEditors: 鸿羽飞舟 2653235481@qq.com
 * @LastEditTime: 2022-10-13 16:46:29
 * @FilePath: \briup-ui\src\pages\admin\category\List.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <!-- 产品栏目管理 -->
  <div>
    <!-- 第一行开始 按钮 -->
    <div class="header">
      <el-form :inline="true" :model="params" class="demo-form-inline">
        <!-- 新增栏目 -->
        <el-form-item>
          <el-button type="primary" @click="toAdd">新增栏目</el-button>
        </el-form-item>
        <!-- 批量删除 -->
        <el-form-item>
          <el-button
            type="primary"
            :disabled="multipleSelection.length === 0"
            @click="selectDelect"
          >批量删除</el-button>
        </el-form-item>
        <!-- 搜索 -->
        <el-form-item>
          <el-input
            v-model="params.name"
            placeholder="请输入名称搜索"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="toSearch">搜索</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 第一行结束 按钮 -->

    <!-- 第二行开始 表格/表单 -->
    <template>
      <el-table
        :data="tableData"
        style="width: 100%"
        row-key="id"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          :reserve-selection="true"
          width="55"
        />
        <el-table-column prop="id" label="栏目编号" sortable />
        <el-table-column prop="name" label="名称">
          <template slot-scope="scope">
            <el-tag type="info">{{ scope.row.name }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="icon" label="栏目图标">
          <template slot-scope="scope">
            <el-popover placement="right" trigger="hover">
              <img
                slot="reference"
                :src="scope.row.icon"
                width="30px"
                alt="加载失败"
              >
              <img width="200px" :src="scope.row.icon" alt="加载失败">
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column prop="num" label="组别号" sortable />
        <el-table-column label="操作" width="160" fixed="right">
          <template slot-scope="scope">
            <el-button-group>
              <!-- 编辑按钮 -->
              <el-button
                type="info"
                icon="el-icon-edit"
                @click="toEdit(scope.row)"
              />
              <!-- 删除按钮 -->
              <el-button
                type="primary"
                icon="el-icon-delete"
                @click="toDelect(scope.row.id)"
              />
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
    </template>
    <!-- 第二行结束 表格/表单 -->

    <!-- 第三行开始 分页 -->
    <div class="category_page">
      <el-pagination
        :current-page="params.page"
        :page-sizes="[2, 5, 10, 20, 50]"
        :page-size="params.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 第三行结束 分页 -->

    <!-- 模态框开始 -->
    <el-dialog :title="title" :visible.sync="visible_mtk" @close="toClose">
      <el-form ref="categoryForm" :model="form" :rules="rules">
        <!-- 栏目名称 -->
        <el-form-item
          label="栏目名称"
          :label-width="formLabelWidth"
          prop="name"
        >
          <el-input v-model="form.name" autocomplete="off" />
        </el-form-item>
        <!-- 组别号 -->
        <el-form-item label="组别号" :label-width="formLabelWidth" prop="num">
          <el-input v-model="form.num" autocomplete="off" />
        </el-form-item>
        <!-- 栏目图标 -->
        <el-form-item
          label="栏目图标"
          :label-width="formLabelWidth"
          prop="icon"
        >
          <el-upload
            class="avatar-uploader"
            :action="uploadFileURL"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="form.icon" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
      </el-form>
      <!-- 按键 取消/确定 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="toClose()">取 消</el-button>
        <el-button type="primary" @click="toSubmit">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 模态框结束 -->
  </div>
</template>

<script>
// 引入
import { uploadFileURL } from '@/utils/config'
import { pageQuery, saveOrUpdate, deleteById } from '@/api/proCategory'

export default {
  data() {
    return {
      // 图片上传路径
      uploadFileURL,
      // 表单对象和分页数据
      params: {
        page: 1,
        pageSize: 10
      },
      // 表格数据
      tableData: [],
      // 总条数
      total: 0,
      // 选中行
      multipleSelection: [],
      // 模态框标题
      title: '',
      // 控制模态框显示与隐藏变量
      visible_mtk: false,
      // 表单对象
      form: {},
      formLabelWidth: '120px',
      //   头像上传变量
      imageUrl: '',
      // 表单校验规则
      rules: {
        name: [{ required: true, message: '请输入栏目名称', trigger: 'blur' }],
        num: [
          {
            required: true,
            message: '请输入栏目组别',
            trigger: 'blur'
          }
        ],
        icon: [{ required: true, message: '请上传封面', trigger: 'change' }]
      },
      // 控制白屏加载动画
      loading: false
    }
  },
  computed: {},
  created() {
    this.getCategoryById()
  },
  mounted() {},
  methods: {
    // 按钮
    // 新增
    toAdd() {
      this.visible_mtk = true
      this.title = '添加栏目信息'
      this.form = {}
      this.imageUrl = ''
    },
    // 批量删除
    selectDelect() {
      const length = this.multipleSelection.length
      this.$confirm('此操作将永久删除所选栏目, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          for (let i = 0; i < length; i++) {
            await deleteById({ id: this.multipleSelection[i] })
          }
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getCategoryById()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 搜索
    toSearch() {
      this.params.page = 1
      this.getCategoryById()
    },
    // 编辑
    toEdit(row) {
      this.title = '修改栏目信息'
      this.visible_mtk = true
      this.form = { ...row }
      this.imageUrl = this.form.icon
    },
    // 删除
    toDelect(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          await deleteById({ id: id })
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getCategoryById()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },

    // 表格/表单
    // 获取数据
    // 根据分页获取对应栏目信息
    async getCategoryById() {
      // 数据获取之前加载动画
      this.loading = true
      for (const key in this.params) {
        // key 属性名
        // this.params[key] 属性值
        if (!this.params[key]) {
          delete this.params[key]
        }
      }
      const res = await pageQuery(this.params)
      // console.log(res, "获取响应");
      this.tableData = res.data.list
      this.total = res.data.total
      // 关闭加载动画
      this.loading = false
    },
    // 获取批量勾选数据
    handleSelectionChange(rows) {
      this.multipleSelection = rows.map((item) => {
        return item.id
      })
    },

    // 保存或更新
    toSubmit() {
      // 校验表单
      this.$refs.categoryForm.validate(async(valid) => {
        if (valid) {
          // 发送保存或者更新请求
          const res = await saveOrUpdate(this.form)
          this.$notify({
            type: 'success',
            message: res.message
          })
          this.visible_mtk = false
          this.getCategoryById()
          this.toClose()
        } else {
          return false
        }
      })
    },

    // 模态框关闭的回调
    toClose() {
      // 重置表单
      setTimeout(() => {
        this.$refs.categoryForm.resetFields()
      }, 500)
      this.visible_mtk = false
    },

    // 图片上传
    // 图片上传成功的方法
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
      // console.log(res);
      this.form.icon = res.data
    },
    // 图片上传之前的方法
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },

    // 分页
    // 页码条数发生改变的方法
    handleSizeChange(pageSize) {
      this.params.pageSize = pageSize
      this.params.page = 1
      this.getCategoryById()
    },
    // 当前页码发生改变触发的方法
    handleCurrentChange(page) {
      this.params.page = page
      this.getCategoryById()
    }
  }
}
</script>
<style scoped>
/* 图片上传 */
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.category_page {
  margin-top: 50px;
}
</style>
